package ini_reader

import (
	"bufio"
	"io"
	"runtime"
	"strings"
)

// commentSymbol based on running os :Linux is ';' and Windows is '#'
var commentSymbol byte

func init() {
	switch runtime.GOOS {
	case "windows":
		commentSymbol = ';'
	case "linux":
		commentSymbol = '#'
	}
}

// Parse : parse the .ini into configuration 
func parse(reader *bufio.Reader) config {

	var secInit section = section{Name: "", Map: map[string]string{}}
	var cfg config = config{Map: map[string]*section{"": &secInit}, CurSec: &secInit}
	
	for {
		fileLine, _, err := reader.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(ErrorReadFile)
		}

		lineStr := string(fileLine)

		// An empty line
		if len(lineStr) == 0 {
			continue
		}

		// A description for section
		if lineStr[0] == commentSymbol {
			continue
		}

		if lineStr[0] == '[' {
			// A section
			index := strings.Index(lineStr, "]")
			secName := strings.TrimSpace(lineStr[1:index])
			cfg.Map[secName] = &section{Name: secName, Map: map[string]string{}}
			cfg.CurSec = cfg.Section(secName)
		} else {
			// A key - value pair
			index := strings.Index(lineStr, "=")
			if index <= 0 {
				continue
			}

			key := strings.TrimSpace(lineStr[:index])
			value := strings.TrimSpace(lineStr[index+1:])
			if len(value) == 0 || len(key) == 0 {
				continue
			}

			cfg.CurSec.Map[key] = value
		}

	}
	return cfg
}

